import requests
import re
import time
import websocket
import json
class AudioSpider:
    headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}
    def __init__(self,) -> None:
        pass

    def get_token(self):
        token_url = "https://zh-cn.text-to-speech.online/static/js/textspeech.js?01"
        res = requests.get(token_url, headers=self.headers)
        url = re.findall(r"'wss:.*?'", res.text, re.S)[0]
        return url.replace("'", "")

    def create_msg(self, path, content_type, content):
        return f"Path: {path}\r\nX-RequestId: 833376F067B64ADCBD30B41FEAC9A125\r\nX-Timestamp: {time.strftime('%Y-%m-%dT%H:%M:%S.271Z', time.gmtime())}\r\nContent-Type: {content_type}\r\n\r\n{content}"

    def get_message_1(self):
        content = json.dumps({"context":{"system":{"name":"SpeechSDK","version":"1.19.0","build":"JavaScript","lang":"JavaScript"},"os":{"platform":"Browser/Win32","name":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36","version":"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"}}})

        return self.create_msg("speech.config", "application/json", content)
        
    def get_message_2(self):
    
        content = json.dumps({"synthesis":{"audio":{"metadataOptions":{"bookmarkEnabled":False,"sentenceBoundaryEnabled":False,"visemeEnabled":False,"wordBoundaryEnabled":False},"outputFormat":"audio-24khz-48kbitrate-mono-mp3"},"language":{"autoDetection":False}}})
        return self.create_msg("synthesis.context", "application/json", content)

    def get_message_3(self, inputs, people_name):
        content = f"""<speak  xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xmlns:emo="http://www.w3.org/2009/10/emotionml" version="1.0" xml:lang="en-US">
    <voice  name="zh-CN-{people_name}Neural">
        <prosody  rate="0%" pitch="0%">{inputs}</prosody>
    </voice>
</speak>"""
        return self.create_msg("ssml", "application/ssml+xml", content)


    def download_audio(self, inputs, people_name, saved_path):
        failed_time = 0
        url = None
        while failed_time < 5:
            try:
                url = self.get_token()
                break
            except:
                time.sleep(1)
                failed_time += 1
                continue
        if url is None:
            raise Exception("获取token失败")

        url = url + "&Authorization=bearer" +"%20" + "undefined&X-ConnectionId=6F3F105155A54672B19361152F744EC2"
        ws = websocket.create_connection(url, timeout=20)

        message1 = self.get_message_1()
        message2 = self.get_message_2()
        message3 = self.get_message_3(inputs, people_name)
        ws.send(message1)
        ws.send(message2)
        ws.send(message3)
        audio_data = b''

        while True:
            msg = ws.recv()
            if isinstance(msg, bytes):
                audio_data += msg.split(b"Path:audio\r\n")[-1]

            elif isinstance(msg, str):
                # 转换结束
                if "Path:turn.end" in msg:
                    break
 

        with open(saved_path, "wb") as f:
            f.write(audio_data)
        print("下载完成")
        return True
            

if __name__ == '__main__':
    audio = AudioSpider()
    audio.download_audio('你好', "Yunxi", "hello.mp3")
    